package etnorservice.etnor_service.controller.project;

import etnorservice.etnor_service.domain.dto.ProjectDTO;
import etnorservice.etnor_service.result.Result;
import etnorservice.etnor_service.service.project.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

@RestController
public class ProjectController {

    @Autowired
    private ProjectService projectService;

    @Value("${project-file.upload.path}")
    private String fileUploadPath;

    @Value("${project-file.download.url}")
    private String fileDownloadUrl;

    @Value("${gitee.owner}")
    private String giteeOwner; // Gitee用户名

    @Value("${gitee.access-token}")
    private String giteeAccessToken; // Gitee访问令牌

    @Value("${gitee.repo-prefix}")
    private String giteeRepoPrefix; // 项目仓库前缀，如"project-"

    /**
     * 创建项目
     */
//    @PostMapping("/system/projects")
//    public Result<ProjectDTO> createProject(@RequestBody ProjectDTO projectDTO) {
//        ProjectDTO result = projectService.createProject(projectDTO);
//        return Result.success(result);
//    }

    /**
     * 获取项目详情 (管理员访问)
     */
    @GetMapping("/system/projects/{id}")
    public Result<ProjectDTO> getProjectAdmin(@PathVariable Long id) {
        ProjectDTO result = projectService.getProjectById(id);
        return Result.success(result);
    }

    /**
     * 获取项目详情 (前台访问)
     */
    @GetMapping("/projects/{id}")
    public Result<ProjectDTO> getProject(@PathVariable Long id) {
        ProjectDTO result = projectService.getProjectById(id);
        return Result.success(result);
    }

    /**
     * 更新项目
     */
    @PutMapping("/system/projects/{id}")
    public Result<ProjectDTO> updateProject(@PathVariable Long id, @RequestBody ProjectDTO projectDTO) {
        ProjectDTO result = projectService.updateProject(id, projectDTO);
        return Result.success(result);
    }

    /**
     * 删除项目
     */
    @DeleteMapping("/system/projects/{id}")
    public Result<Void> deleteProject(@PathVariable Long id, @RequestParam Long creatorId) {
        projectService.deleteProject(id, creatorId);
        return Result.success("项目删除成功");
    }

    /**
     * 发布项目
     */
    @PostMapping("/system/projects/{id}/publish")
    public Result<Void> publishProject(@PathVariable Long id, @RequestParam Long creatorId) {
        projectService.publishProject(id, creatorId);
        return Result.success("项目发布成功");
    }

    /**
     * 获取用户的项目列表 (管理员访问)
     */
    @GetMapping("/system/projects/user/{userId}")
    public Result<List<ProjectDTO>> getUserProjectsAdmin(@PathVariable Long userId) {
        List<ProjectDTO> projects = projectService.getUserProjects(userId);
        return Result.success(projects);
    }

    /**
     * 获取用户的项目列表 (前台访问)
     */
    @GetMapping("/projects/user/{userId}")
    public Result<List<ProjectDTO>> getUserProjects(@PathVariable Long userId) {
        List<ProjectDTO> projects = projectService.getUserProjects(userId);
        return Result.success(projects);
    }

    /**
     * 获取已发布的项目列表 (管理员访问)
     */
    @GetMapping("/system/projects")
    public Result<List<ProjectDTO>> getPublishedProjectsAdmin(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        List<ProjectDTO> projects = projectService.getPublishedProjects(page, size);
        return Result.success(projects);
    }

    /**
     * 获取已发布的项目列表 (前台访问)
     */
    @GetMapping("/projects")
    public Result<List<ProjectDTO>> getPublishedProjects(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        List<ProjectDTO> projects = projectService.getPublishedProjects(page, size);
        return Result.success(projects);
    }

    /**
     * 获取免费/付费项目列表 (管理员访问)
     */
    @GetMapping("/system/projects/free")
    public Result<List<ProjectDTO>> getFreeProjectsAdmin(
            @RequestParam boolean isFree,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        List<ProjectDTO> projects = projectService.getProjectsByIsFree(isFree, page, size);
        return Result.success(projects);
    }

    /**
     * 获取免费/付费项目列表 (前台访问)
     */
    @GetMapping("/projects/free")
    public Result<List<ProjectDTO>> getFreeProjects(
            @RequestParam boolean isFree,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        List<ProjectDTO> projects = projectService.getProjectsByIsFree(isFree, page, size);
        return Result.success(projects);
    }

    /**
     * 上传项目文件
     */
    @PostMapping("/system/projects/upload")
    public Result<String> uploadProjectFile(@RequestParam("file") MultipartFile file) {
        System.out.println("调用文件上传============");
        if (file.isEmpty()) {
            return Result.error("上传文件不能为空");
        }

        try {
            // 创建目标目录
            File uploadDir = new File(fileUploadPath);
            if (!uploadDir.exists()) {
                boolean created = uploadDir.mkdirs();
                if (!created) {
                    return Result.error("无法创建上传目录: " + fileUploadPath);
                }
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                return Result.error("无效的文件名");
            }

            String extension = originalFilename.contains(".") ?
                    originalFilename.substring(originalFilename.lastIndexOf(".")) : "";
            String newFilename = UUID.randomUUID().toString() + extension;

            // 保存文件
            Path targetPath = Paths.get(fileUploadPath, newFilename);
            Files.copy(file.getInputStream(), targetPath);

            // 返回文件路径
            return Result.success(newFilename);
        } catch (IOException e) {
            e.printStackTrace(); // 打印详细错误信息到日志
            return Result.error("文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 上传项目截图
     */
    @PostMapping("/system/projects/upload/screenshot")
    public Result<String> uploadScreenshot(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error("上传图片不能为空");
        }

        try {
            // 创建目标目录
            String screenshotPath = fileUploadPath + "/screenshots";
            File uploadDir = new File(screenshotPath);
            if (!uploadDir.exists()) {
                boolean created = uploadDir.mkdirs();
                if (!created) {
                    return Result.error("无法创建截图目录: " + screenshotPath);
                }
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                return Result.error("无效的文件名");
            }

            String extension = originalFilename.contains(".") ?
                    originalFilename.substring(originalFilename.lastIndexOf(".")) : "";
            String newFilename = UUID.randomUUID().toString() + extension;

            // 保存文件
            Path targetPath = Paths.get(screenshotPath, newFilename);
            Files.copy(file.getInputStream(), targetPath);

            // 返回文件路径
            return Result.success("/screenshots/" + newFilename);
        } catch (IOException e) {
            e.printStackTrace(); // 打印详细错误信息到日志
            return Result.error("图片上传失败: " + e.getMessage());
        }
    }

    /**
     * 生成下载令牌 (管理员访问)
     */
    @PostMapping("/system/projects/{id}/download-token")
    public Result<String> generateDownloadTokenAdmin(
            @PathVariable Long id,
            @RequestParam(required = false) Long userId,
            HttpServletRequest request) {
        String ipAddress = request.getRemoteAddr();
        String token = projectService.generateDownloadToken(userId, id, ipAddress);
        return Result.success(token);
    }

    /**
     * 生成下载令牌 (前台访问)
     */
    @PostMapping("/projects/{id}/download-token")
    public Result<String> generateDownloadToken(
            @PathVariable Long id,
            @RequestParam(required = false) Long userId,
            HttpServletRequest request) {
        String ipAddress = request.getRemoteAddr();
        String token = projectService.generateDownloadToken(userId, id, ipAddress);
        return Result.success(token);
    }

    /**
     * 获取下载URL (后台管理)
     */
    @GetMapping("/system/projects/download")
    public Result<String> downloadProjectAdmin(
            @RequestParam String token,
            HttpServletRequest request) {
        String ipAddress = request.getRemoteAddr();
        String filePath = projectService.validateDownloadToken(token, ipAddress);
        return Result.success(fileDownloadUrl + filePath);
    }

    /**
     * 获取下载URL (前台访问)
     */
    @GetMapping("/projects/download")
    public Result<String> downloadProject(
            @RequestParam String token,
            HttpServletRequest request) {
        String ipAddress = request.getRemoteAddr();
        String filePath = projectService.validateDownloadToken(token, ipAddress);
        return Result.success(fileDownloadUrl + filePath);
    }
    /**
     * 获取项目分类列表
     */
    @GetMapping("/system/projects/categories")
    public Result<List<Map<String, Object>>> getCategories() {
        List<Map<String, Object>> categories = projectService.getAllCategories();
        return Result.success(categories);
    }

    /**
     * 获取项目标签列表
     */
    @GetMapping("/system/projects/tags")
    public Result<List<Map<String, Object>>> getTags() {
        List<Map<String, Object>> tags = projectService.getAllTags();
        return Result.success(tags);
    }


    /**
     * 使用Gitee创建项目仓库
     */
    @PostMapping("/system/projects/create-repo")
    public Result<Map<String, String>> createGiteeRepo(@RequestParam String projectName, @RequestParam String description) {
        try {
            // 仓库名，使用前缀+随机字符串，避免名称冲突
            String repoName = giteeRepoPrefix + UUID.randomUUID().toString().substring(0, 8);

            // 构建Gitee API请求
            String apiUrl = "https://gitee.com/api/v5/user/repos";
            Map<String, Object> params = new HashMap<>();
            params.put("access_token", giteeAccessToken);
            params.put("name", repoName);
            params.put("description", description);
            params.put("private", true); // 私有仓库
            params.put("auto_init", true); // 初始化仓库

            // 发送请求创建仓库
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<Map> response = restTemplate.postForEntity(apiUrl, params, Map.class);

            if (response.getStatusCode().is2xxSuccessful()) {
                Map<String, String> result = new HashMap<>();
                result.put("repoName", repoName);
                result.put("httpsUrl", "https://gitee.com/" + giteeOwner + "/" + repoName + ".git");
                result.put("sshUrl", "git@gitee.com:" + giteeOwner + "/" + repoName + ".git");
                result.put("webUrl", "https://gitee.com/" + giteeOwner + "/" + repoName);
                result.put("downloadUrl", "https://gitee.com/" + giteeOwner + "/" + repoName + "/repository/archive/master.zip");

                return Result.success(result);
            } else {return Result.error("创建Gitee仓库失败: " + response.getBody());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("创建Gitee仓库异常: " + e.getMessage());
        }
    }

    /**
     * 上传文件到Gitee仓库
     */
    @PostMapping("/system/projects/upload-to-gitee")
    public Result<String> uploadToGitee(
            @RequestParam("file") MultipartFile file,
            @RequestParam("repoName") String repoName) {

        if (file.isEmpty()) {
            return Result.error("上传文件不能为空");
        }

        try {
            // 获取文件名和内容
            String fileName = file.getOriginalFilename();
            if (fileName == null) {
                return Result.error("无效的文件名");
            }

            // 临时保存文件
            File tempFile = File.createTempFile("upload", fileName);
            file.transferTo(tempFile); // 构建Gitee API请求上传文件
            String apiUrl = "https://gitee.com/api/v5/repos/" + giteeOwner + "/" + repoName + "/contents/" + fileName;

            // 读取文件内容并Base64编码
            byte[] fileContent = Files.readAllBytes(tempFile.toPath());
            String encodedContent = Base64.getEncoder().encodeToString(fileContent);

            // 删除临时文件
            tempFile.delete();

            // 准备请求参数
            Map<String, Object> params = new HashMap<>();
            params.put("access_token", giteeAccessToken);
            params.put("content", encodedContent);
            params.put("message", "Upload " + fileName);

            // 发送请求上传文件
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<Map> response = restTemplate.postForEntity(apiUrl, params, Map.class);

            if (response.getStatusCode().is2xxSuccessful()) {
                // 返回下载URL
                String downloadUrl = "https://gitee.com/" + giteeOwner + "/" + repoName + "/raw/master/" + fileName;
                return Result.success(downloadUrl);
            } else {
                return Result.error("上传文件到Gitee失败: " + response.getBody());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("上传文件到Gitee异常: " + e.getMessage());
        }
    }
    /**
     * 修改项目实体以存储Gitee仓库信息
     */
    @PostMapping("/system/projects")
    public Result<ProjectDTO> createProject(@RequestBody ProjectDTO projectDTO) {
        System.out.println(projectDTO);
        // 调用原有的创建项目方法
        ProjectDTO result = projectService.createProject(projectDTO);
        return Result.success(result);
    }


    /**
     * 上传项目截图到Gitee仓库
     */
    @PostMapping("/system/projects/upload-screenshot-to-gitee")
    public Result<String> uploadScreenshotToGitee(
            @RequestParam("file") MultipartFile file,
            @RequestParam("repoName") String repoName) {

        if (file.isEmpty()) {
            return Result.error("上传图片不能为空");
        }

        try {
            // 获取文件内容
            byte[] fileContent = file.getBytes();
            String originalFilename = file.getOriginalFilename();

            if (originalFilename == null) {
                return Result.error("无效的文件名");
            }

            // 生成唯一文件名，保留原始扩展名
            String extension = originalFilename.contains(".") ?
                    originalFilename.substring(originalFilename.lastIndexOf(".")) : "";
            String fileName = "screenshot-" + UUID.randomUUID().toString().substring(0, 8) + extension;

            // Base64编码文件内容
            String content = Base64.getEncoder().encodeToString(fileContent);

            // 构建API请求
            Map<String, Object> params = new HashMap<>();
            params.put("access_token", giteeAccessToken);
            params.put("content", content);
            params.put("message", "上传截图: " + fileName);

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(params, headers);

            // 调用Gitee API上传文件到screenshots目录
            String apiUrl = "https://gitee.com/api/v5/repos/" + giteeOwner + "/" + repoName +
                    "/contents/screenshots/" + fileName;

            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<Map> response = restTemplate.postForEntity(apiUrl, requestEntity, Map.class);

            if (response.getStatusCode().is2xxSuccessful()) {
                // 返回可直接访问的图片URL
                String imageUrl = "https://gitee.com/" + giteeOwner + "/" + repoName +
                        "/raw/master/screenshots/" + fileName;
                return Result.success(imageUrl);
            } else {
                return Result.error("上传截图到Gitee失败: " + response.getBody());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("上传截图到Gitee异常: " + e.getMessage());
        }
    }


//    /**
//     * 上传项目截图到Gitee仓库
//     */
//    @PostMapping("/system/projects/upload-screenshot-to-gitee")
//    public Result<String> uploadScreenshotToGitee(
//            @RequestParam("file") MultipartFile file,
//            @RequestParam("repoName") String repoName,
//            @RequestParam(value = "fileName", required = false) String fileName) {
//
//        if (file.isEmpty()) {
//            return Result.error("上传图片不能为空");
//        }
//
//        try {
//            // 获取文件内容
//            byte[] fileContent = file.getBytes();
//            String originalFilename = file.getOriginalFilename();
//
//            if (originalFilename == null) {
//                return Result.error("无效的文件名");
//            }
//
//            // 使用提供的文件名或生成一个
//            if (fileName == null || fileName.isEmpty()) {
//                String extension = originalFilename.contains(".") ?
//                        originalFilename.substring(originalFilename.lastIndexOf(".")) : "";
//                fileName = "screenshot-" + UUID.randomUUID().toString().substring(0, 8) + extension;
//            }
//
//            // Base64编码文件内容
//            String content = Base64.getEncoder().encodeToString(fileContent);
//
//            // 构建API请求
//            Map<String, Object> params = new HashMap<>();
//            params.put("access_token", giteeAccessToken);
//            params.put("content", content);
//            params.put("message", "上传截图: " + fileName);
//
//            // 设置请求头
//            HttpHeaders headers = new HttpHeaders();
//            headers.setContentType(MediaType.APPLICATION_JSON);
//
//            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(params, headers);
//
//            // 确保screenshots目录存在，如果不存在则创建
//            ensureScreenshotsDirectoryExists(repoName);
//
//            // 调用Gitee API上传文件到screenshots目录
//            String apiUrl = "https://gitee.com/api/v5/repos/" + giteeOwner + "/" + repoName +
//                    "/contents/screenshots/" + fileName;
//
//            RestTemplate restTemplate = new RestTemplate();
//            ResponseEntity<Map> response = restTemplate.postForEntity(apiUrl, requestEntity, Map.class);
//
//            if (response.getStatusCode().is2xxSuccessful()) {
//                // 返回可直接访问的图片URL
//                String imageUrl = "https://gitee.com/" + giteeOwner + "/" + repoName +
//                        "/raw/master/screenshots/" + fileName;
//                return Result.success(imageUrl);
//            } else {
//                return Result.error("上传截图到Gitee失败: " + response.getBody());
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return Result.error("上传截图到Gitee异常: " + e.getMessage());
//        }
//    }

    /**
     * 确保screenshots目录存在
     */
    private void ensureScreenshotsDirectoryExists(String repoName) {
        try {
            // 检查screenshots目录是否存在
            String checkUrl = "https://gitee.com/api/v5/repos/" + giteeOwner + "/" + repoName +
                    "/contents/screenshots?access_token=" + giteeAccessToken;

            RestTemplate restTemplate = new RestTemplate();
            try {
                restTemplate.getForEntity(checkUrl, Object.class);
                // 如果没有抛出异常，说明目录存在
                return;
            } catch (HttpClientErrorException e) {
                // 404 表示目录不存在，需要创建
                if (e.getStatusCode().value() != 404) {
                    throw e;
                }
            }

            // 创建screenshots目录
            Map<String, Object> params = new HashMap<>();
            params.put("access_token", giteeAccessToken);
            params.put("content", Base64.getEncoder().encodeToString("# Screenshots".getBytes()));
            params.put("message", "创建 screenshots 目录");

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(params, headers);

            // 调用Gitee API创建README.md文件来创建目录
            String apiUrl = "https://gitee.com/api/v5/repos/" + giteeOwner + "/" + repoName +
                    "/contents/screenshots/README.md";

            restTemplate.postForEntity(apiUrl, requestEntity, Map.class);
        } catch (Exception e) {
            // 记录异常但不中断流程
            e.printStackTrace();
        }
    }

    /**
     * 删除Gitee仓库中的文件
     */
    @DeleteMapping("/system/projects/delete-gitee-file")
    public Result<Boolean> deleteGiteeFile(
            @RequestParam("repoName") String repoName,
            @RequestParam("filePath") String filePath) {

        try {
            // 先获取文件的SHA
            String getFileUrl = "https://gitee.com/api/v5/repos/" + giteeOwner + "/" + repoName +
                    "/contents/" + filePath + "?access_token=" + giteeAccessToken;

            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<Map> fileResponse = restTemplate.getForEntity(getFileUrl, Map.class);

            if (!fileResponse.getStatusCode().is2xxSuccessful()) {
                return Result.error("获取文件信息失败");
            }

            String sha = (String) fileResponse.getBody().get("sha");

            // 构建删除请求
            Map<String, Object> params = new HashMap<>();
            params.put("access_token", giteeAccessToken);
            params.put("message", "删除文件: " + filePath);
            params.put("sha", sha);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(params, headers);

            // 发送删除请求
            ResponseEntity<Map> deleteResponse = restTemplate.exchange(
                    getFileUrl,
                    HttpMethod.DELETE,
                    requestEntity,
                    Map.class
            );

            if (deleteResponse.getStatusCode().is2xxSuccessful()) {
                return Result.success(true);
            } else {
                return Result.error("删除文件失败: " + deleteResponse.getBody());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除文件异常: " + e.getMessage());
        }
    }
}